package dissertation.extensions.generate.webservice.webclass.control;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.hint.HintManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiModifierList;
import dissertation.common.utils.WriteAction;
import dissertation.services.ejbclass.EJBClassService;
import dissertation.services.ejbclass.IEJBClassService;
import org.jetbrains.annotations.NotNull;

import static dissertation.common.constants.Constants.*;

public class GenerateWebServiceCodeInsightActionHandler implements CodeInsightActionHandler {
    private IEJBClassService ejbClassService;

    public GenerateWebServiceCodeInsightActionHandler() {
        ejbClassService = new EJBClassService();
    }

    @Override
    public void invoke(@NotNull final Project project, @NotNull Editor editor, @NotNull PsiFile file) {
        final PsiClass aClass = OverrideImplementUtil.getContextClass(project, editor, file, true);
        if (aClass == null) {
            HintManager.getInstance().showErrorHint(editor, "An Error occurred while retrieving the containing Java file.");
            return;
        }

        PsiModifierList modifierList = aClass.getModifierList();
        if (modifierList != null && modifierList.findAnnotation(WEB_SERVICE_PACKAGE + "." + WEB_SERVICE_ANNOTATION_NAME) == null) {
            Runnable cmd = new Runnable() {
                @Override
                public void run() {
                    ejbClassService.addImportStatement(aClass, WEB_SERVICE_PACKAGE);
                    ejbClassService.annotateClass(aClass, WEB_SERVICE_ANNOTATION_NAME);
                }
            };
            CommandProcessor.getInstance().executeCommand(project, new WriteAction(cmd), null, null);
        } else {
            HintManager.getInstance().showErrorHint(editor, "This class is already a web service.");
        }
    }

    public boolean startInWriteAction() {
        return false;
    }
}
